package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.GwPlatformAccountRole;
import com.ruoyi.system.mapper.GwPlatformAccountRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.BaseService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.GwPlatformAccountMapper;
import com.ruoyi.system.domain.GwPlatformAccount;
import com.ruoyi.system.service.IGwPlatformAccountService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 平台账号管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-06
 */
@Service
public class GwPlatformAccountServiceImpl extends BaseService implements IGwPlatformAccountService
{
    @Resource
    private GwPlatformAccountMapper gwPlatformAccountMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private GwPlatformAccountRoleMapper accountRoleMapper;
    private static final String AVATAR = "https://gowork365.com/prod-api/profile/mini/index/enterpriseLogo.png";

    /**
     * 查询平台账号管理
     * 
     * @param id 平台账号管理主键
     * @return 平台账号管理
     */
    @Override
    public GwPlatformAccount selectGwPlatformAccountById(String id)
    {
        return gwPlatformAccountMapper.selectGwPlatformAccountById(id);
    }

    /**
     * 查询平台账号管理列表
     * 
     * @param gwPlatformAccount 平台账号管理
     * @return 平台账号管理
     */
    @Override
    public List<GwPlatformAccount> selectGwPlatformAccountList(GwPlatformAccount gwPlatformAccount)
    {
        if(StringUtils.isNotEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            gwPlatformAccount.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        }
        List<GwPlatformAccount> accountList = gwPlatformAccountMapper.selectList(gwPlatformAccount);
        accountList.forEach(k->{
           String roleNames =  gwPlatformAccountMapper.selectRoleNamesByPlatformAccount(k.getId());
           k.setRoleNames(roleNames);
        });
        return accountList;
    }

    /**
     * 新增平台账号管理
     * 
     * @param gwPlatformAccount 平台账号管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertGwPlatformAccount(GwPlatformAccount gwPlatformAccount)
    {
        if(!checkPhone(gwPlatformAccount.getPhone())){
            return AjaxResult.error("该手机号已注册过，不可重复注册");
        }

        gwPlatformAccount.setId(IdUtils.fastSimpleUUID());
        gwPlatformAccount.setCreateBy(SecurityUtils.getUserId()+"");
        gwPlatformAccount.setCreateTime(DateUtils.getNowDate());
        gwPlatformAccount.setUpdateBy(SecurityUtils.getUserId()+"");
        gwPlatformAccount.setUpdateTime(DateUtils.getNowDate());
        gwPlatformAccount.setPassword(SecurityUtils.encryptPassword(gwPlatformAccount.getPassword()));
        gwPlatformAccount.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        int num = gwPlatformAccountMapper.insertGwPlatformAccount(gwPlatformAccount);
        //统一登录账号管理，将账号插入sys_user一份
        SysUser sysUser = new SysUser();
        sysUser.setUserType(UserType.PLATFORM_USER.getCode());
        sysUser.setPhonenumber(gwPlatformAccount.getPhone());
        sysUser.setNickName(gwPlatformAccount.getUserName());
        sysUser.setChannelId(gwPlatformAccount.getId());
        sysUser.setPassword(gwPlatformAccount.getPassword());
        sysUser.setSignOpenId(createCertificationOpenId());
        sysUser.setAvatar(AVATAR);
        sysUserMapper.insertUser(sysUser);

        if(!StringUtils.isBlank(gwPlatformAccount.getRole())){
            String[] roles = gwPlatformAccount.getRole().split(",");
            for(String roleId :roles){
                GwPlatformAccountRole accountRole = new GwPlatformAccountRole();
                accountRole.setId(IdUtils.fastSimpleUUID());
                accountRole.setAccountId(gwPlatformAccount.getId());
                accountRole.setPlatformRoleId(roleId);
                accountRoleMapper.insertGwPlatformAccountRole(accountRole);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改平台账号管理
     * 
     * @param gwPlatformAccount 平台账号管理
     * @return 结果
     */
    @Override
    public int updateGwPlatformAccount(GwPlatformAccount gwPlatformAccount)
    {
        gwPlatformAccount.setUpdateBy(SecurityUtils.getUserId()+"");
        gwPlatformAccount.setUpdateTime(DateUtils.getNowDate());
        //修改功能不支持修改密码
        gwPlatformAccount.setPassword(null);
        int num = gwPlatformAccountMapper.updateGwPlatformAccount(gwPlatformAccount);
        //同步变更sys_user表
        SysUser sysUser  = sysUserMapper.selectUserByChannelId(gwPlatformAccount.getId());
        if(sysUser!=null){
            sysUser.setNickName(gwPlatformAccount.getNickName());
            sysUser.setPhonenumber(gwPlatformAccount.getPhone());
            sysUserMapper.updateUser(sysUser);
        }
        GwPlatformAccountRole accountRole = new GwPlatformAccountRole();
        accountRole.setAccountId(gwPlatformAccount.getId());
        List<GwPlatformAccountRole> accountRoleList = accountRoleMapper.selectGwPlatformAccountRoleList(accountRole);
        if(!CollectionUtils.isEmpty(accountRoleList)){
            accountRoleList.forEach(k->{
                accountRoleMapper.deleteGwPlatformAccountRoleById(k.getId());
            });
        }

        if(!StringUtils.isBlank(gwPlatformAccount.getRole())) {
            String[] roles = gwPlatformAccount.getRole().split(",");
            for (String roleId : roles) {
                GwPlatformAccountRole vo = new GwPlatformAccountRole();
                vo.setId(IdUtils.fastSimpleUUID());
                vo.setAccountId(gwPlatformAccount.getId());
                vo.setPlatformRoleId(roleId);
                accountRoleMapper.insertGwPlatformAccountRole(vo);
            }
        }

        return num;
    }

    /**
     * 批量删除平台账号管理
     * 
     * @param ids 需要删除的平台账号管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGwPlatformAccountByIds(String[] ids)
    {
        int num = gwPlatformAccountMapper.deleteGwPlatformAccountByIds(ids);
        for(String id:ids){
            SysUser sysUser  = sysUserMapper.selectUserByChannelId(id);
            if(sysUser!=null){
                sysUserMapper.deleteUserById(sysUser.getUserId());
            }
        }
        return num;
    }

    /**
     * 删除平台账号管理信息
     * 
     * @param id 平台账号管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGwPlatformAccountById(String id)
    {
        int num = gwPlatformAccountMapper.deleteGwPlatformAccountById(id);
        SysUser sysUser  = sysUserMapper.selectUserByChannelId(id);
        if(sysUser!=null){
            sysUserMapper.deleteUserById(sysUser.getUserId());
        }
        return num;
    }

    @Override
    public List<GwPlatformAccount> myEnterpriseList(GwPlatformAccount gwPlatformAccount) {
        if(StringUtils.isBlank(SecurityUtils.getLoginUser().getEnterpriseId())){
            return Lists.newArrayList();
        }
        gwPlatformAccount.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        List<GwPlatformAccount> accountList = gwPlatformAccountMapper.selectList(gwPlatformAccount);
        accountList.forEach(k->{
            String roleNames =  gwPlatformAccountMapper.selectRoleNamesByPlatformAccount(k.getId());
            k.setRoleNames(roleNames);
        });
        return accountList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(GwPlatformAccount gwPlatformAccount) {
        GwPlatformAccount account = new GwPlatformAccount();
        account.setId(gwPlatformAccount.getId());
        account.setStatus(gwPlatformAccount.getStatus());
        int num = gwPlatformAccountMapper.updateGwPlatformAccount(account);

        //同步更新sys_user用户表
        SysUser sysUser  = sysUserMapper.selectUserByChannelId(gwPlatformAccount.getId());
        if(sysUser!=null){
            sysUser.setStatus(gwPlatformAccount.getStatus());
            sysUserMapper.updateUser(sysUser);
        }
        return num;
    }

    @Override
    public int resetPassword(GwPlatformAccount gwPlatformAccount) {
        GwPlatformAccount account = new GwPlatformAccount();
        account.setId(gwPlatformAccount.getId());
        account.setPassword(SecurityUtils.encryptPassword(gwPlatformAccount.getPassword()));
        int num = gwPlatformAccountMapper.updateGwPlatformAccount(account);

        //同步更新sys_user用户表
        SysUser sysUser  = sysUserMapper.selectUserByChannelId(gwPlatformAccount.getId());
        if(sysUser!=null){
            sysUser.setPassword(SecurityUtils.encryptPassword(gwPlatformAccount.getPassword()));
            sysUserMapper.updateUser(sysUser);
        }
        return num;
    }
}
